<script>
	import {
		mapState,
		mapMutations
	} from 'vuex';
	// #ifdef APP-PLUS
	import {
		MainActivity
	} from "@/uni_modules/my-scheme";
	import {
		notificationTexts
	} from "@/uni_modules/tq-gt-notice";
	// #endif
	// #ifdef WEB
	import Notify from "@wcjiang/notify";
	import Json from "@/store/Json";
	// #endif
	import {
		_getLatestVersion
	} from '@/service/version.js'

	export default {
		data() {
			return {
				socketTask: null,
				// 确保websocket是打开状态
				is_open_socket: false,
				account_user: '',
				eventBus: new Vue() //创建一个全局事件总线对象
			}
		},

		 onLaunch: async function() {
			console.log('App Launch');
			// #ifdef APP-PLUS
			plus.android.requestPermissions(["android.permission.BLUETOOTH", "android.permission.BLUETOOTH_ADMIN",
				"android.permission.ACCESS_BACKGROUND_LOCATION", "android.permission.ACCESS_COARSE_LOCATION",
				'android.permission.READ_EXTERNAL_STORAGE', 'android.permission.WRITE_EXTERNAL_STORAGE'
			], (
				res) => {
				console.log(res)

			}, e => {
				console.log(e)
			});
			// #endif
			// 检查更新
			await this.checkUpdate()
		},
		onShow: function() {
			console.log('App Show');
			this.connectSocketInit(); // 在应用显示时建立WebSocket连接
			//
			// #ifdef APP-PLUS
			let args = plus.runtime.arguments;
			if (args) {
				let path = args.split("://")[1] || '';
				let page = args.split("?page=")[1];
				console.log(page)
				if (path.startsWith("jump") && page) {
					uni.navigateTo({
						url: page,
						complete: (res) => {
							plus.runtime.arguments = ""; // 清空参数
						}
					});
				}
			}
			// #endif
		},
		onHide: function() {
			console.log('App Hide');
			// this.socketTask.close(); // 在应用关闭时断开WebSocket连接
		},
		created() {
			let self = this;
			//在页面加载时读取localStorage里的状态信息
			// uni.getStorage({
			//   key: 'messageStore',
			//   success:(res) =>{
			//     console.log(this.$store);
			//     console.log(res.data);
			//     console.log(this.$store.state);
			//     // self.$store.replaceState(Object.assign(self.$store.state, JSON.parse(res.data)));
			//     let userInfo = JSON.parse(res.data).userInfo;
			//     console.log(res.data)
			//     // #ifdef APP-PLUS
			//     notificationTexts({
			//       title: "登录成功",
			//       texts: [
			//         `用户：${userInfo.name}`
			//       ],
			//       cancel: true,
			//       lockShow: true,
			//       url: ``
			//     });
			//     // #endif
			//
			//     console.log("更新登录信息成功")
			//   }
			// });
			uni.$on('AccountToApp', (data) => { // 在这里为函数命名
				this.account_user = data;
				this.connectSocketInit(); // 在account_user变化时重新连接websocket
			});
		},
		//使用了watch来监听account_user的变化,当account_user发生变化时调用connectSocketInit方法
		watch: {
			account_user(newVal) {
				if (newVal) {
					this.connectSocketInit(); // 在account_user变化时重新连接websocket
				}
			}
		},
		methods: {
			//26940165678266
			sendExperimentNotification(historySerialnum, title, time, person) {
				// #ifdef WEB
				const notify = new Notify({
					message: "实验完成", // 标题
					effect: "scroll", // flash | scroll 闪烁还是滚动
					openurl: ``, // 点击弹窗打开连接地址
					onclick: () => {
						notify.close(); // 关闭弹窗
						uni.navigateTo({
							url: `/pages/expertrecord/expertrecord?serialnum_history=${historySerialnum}`
						});
					},
					// 标题闪烁，或者滚动速度
					interval: 1000,
					// chrome浏览器通知
					notification: {
						title: "实验完成", // 设置标题
						icon: "", // 设置图标 icon 默认为 Favicon
						body: `已完成实验：${title}\n实验时间：${time}\n实验人员：${person}` // 设置消息内容
					},
				});
				notify.notify({});
				// #endif
				// #ifdef APP-PLUS
				notificationTexts({
					title: "实验完成",
					texts: [
						`已完成实验：${title}`,
						`实验时间：${time}`,
						`实验人员：${person}`
					],
					cancel: true,
					lockShow: true,
					url: `intelligentlaboratory://jump?page=/pages/expertrecord/expertrecord?serialnum_history=${historySerialnum}`
				})
				// #endif
			},
			connectSocketInit() {
				// 创建一个this.socketTask对象【发送、接收、关闭socket都由这个对象操作】
				this.socketTask = uni.connectSocket({
					url: 'ws://43.142.102.167:8088/woonsocket/' + this.account_user,
					success(data) {
						console.log("APP_websocket连接成功");
					},
				});
				this.socketTask.onOpen((res) => {
					console.log(" WebSocket连接正常打开中...！");
					this.is_open_socket = true;
				});

				this.socketTask.onMessage((res) => {
					console.log("收到服务器内容：");
					console.log(res.data);
					let data = JSON.parse(res.data),
						content = data.content;
					// {"content":"1分析 2024-11-23T10:44:28 onefeifan"}
					if (content) {
						this.sendExperimentNotification(content.split(" ")[0], content.split(" ")[1], content
							.split(" ")[2], content.split(" ")[3]);
					}
					// 触发全局事件，将数据传递给其他App界面
					this.eventBus.$emit('websocketData', res.data);
				});

				this.socketTask.onClose(() => {
					console.log("WebSocket已经被关闭了");
					this.is_open_socket = false;
				});
			},
      async checkUpdate() {
        try {
          let currentVersion = "";
          let latestVersion = "";
         
          plus.runtime.getProperty(plus.runtime.appid, async (wgtinfo) => {
            currentVersion = wgtinfo.version;
            // latestVersion = await this.getLatestVersion(); // 在回调内获取最新版本
			let res=await this.getLatestVersion()
			latestVersion= res.version.split('v')[1];
			let brief =res.brief;
            
            // Ensure versions have 'v' prefix
            currentVersion = this.ensureVersionPrefix(currentVersion);
            latestVersion = this.ensureVersionPrefix(latestVersion);
            
            console.log("Current:", currentVersion);
            console.log("Latest:", latestVersion);
            // 这里可以执行版本比较等后续操作
            console.log(this.compareVersion(currentVersion, latestVersion));
            if (this.compareVersion(currentVersion, latestVersion) < 0) {
              // console.log(123);
              // 显示更新弹窗
              setTimeout(()=>{
                uni.navigateTo({
                  url: '/pages/update/update',
                  success: (res) => {
                    res.eventChannel.emit('updateInfo', {
                      currentVersion,
                      latestVersion,
                      description: brief,
                      forceUpdate: false
                    })
                  },
                  fail:(error)=>{
                    console.log(error)
                  }
                })
              },500)
            }
          });

        } catch (error) {
          console.error('检查更新失败:', error)
        }
			},
			
			// Helper function to ensure version has 'v' prefix
			ensureVersionPrefix(version) {
				if (!version.startsWith('v')) {
					return 'v' + version;
				}
				return version;
			},
			
			async getLatestVersion() {
				const res = await _getLatestVersion();
				return res.data;
				return
			},

			// 版本号比较
			compareVersion(v1, v2) {

				const v1Parts = v1.split('.').map(Number)
				const v2Parts = v2.split('.').map(Number)
				for (let i = 0; i < Math.max(v1Parts.length, v2Parts.length); i++) {
					const v1Part = v1Parts[i] || 0
					const v2Part = v2Parts[i] || 0

					if (v1Part < v2Part) return -1
					if (v1Part > v2Part) return 1
				}

				return 0
			},
			
		},
	}
</script>

<style>
	/************************************************************
** 请将全局样式拷贝到项目的全局 CSS 文件或者当前页面的顶部 **
** 否则页面将无法正常显示                                **
************************************************************/

	/* 确保 uni.showModal 弹窗显示在最上层 */
	uni-modal {
		z-index: 19999 !important;
	}
	
	/* 确保 uni.showToast 提示显示在最上层 */
	uni-toast {
		z-index: 19999 !important;
	}

	html {
		font-size: 16px;
	}

	body {
		margin: 0;
		font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans',
			'Droid Sans', 'Helvetica Neue', 'Microsoft Yahei', sans-serif;
		-webkit-font-smoothing: antialiased;
		-moz-osx-font-smoothing: grayscale;
	}

	view,
	image,
	text {
		box-sizing: border-box;
		flex-shrink: 0;
	}

	.flex-row {
		display: flex;
		flex-direction: row;
	}

	.flex-col {
		display: flex;
		flex-direction: column;
	}

	.justify-start {
		justify-content: flex-start;
	}

	.justify-end {
		justify-content: flex-end;
	}

	.justify-center {
		justify-content: center;
	}

	.justify-between {
		justify-content: space-between;
	}

	.justify-around {
		justify-content: space-around;
	}

	.justify-evenly {
		justify-content: space-evenly;
	}

	.items-start {
		align-items: flex-start;
	}

	.items-end {
		align-items: flex-end;
	}

	.items-center {
		align-items: center;
	}

	.items-baseline {
		align-items: baseline;
	}

	.items-stretch {
		align-items: stretch;
	}

	.self-start {
		align-self: flex-start;
	}

	.self-end {
		align-self: flex-end;
	}

	.self-center {
		align-self: center;
	}

	.self-baseline {
		align-self: baseline;
	}

	.self-stretch {
		align-self: stretch;
	}

	.flex-1 {
		flex: 1 1 0%;
	}

	.flex-auto {
		flex: 1 1 auto;
	}

	.grow {
		flex-grow: 1;
	}

	.grow-0 {
		flex-grow: 0;
	}

	.shrink {
		flex-shrink: 1;
	}

	.shrink-0 {
		flex-shrink: 0;
	}

	.relative {
		position: relative;
	}

	//#app {
	//  width: 100vw;
	//  height: 100vh;
	//}
</style>